//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.tl.satoken.controller;

import com.tl.satoken.domain.entity.MBTISquare;
import com.tl.satoken.domain.entity.Player;
import com.tl.satoken.domain.entity.RoomJoinResult;
import com.tl.satoken.listener.WebSocketEventListener;
import com.tl.satoken.service.RoomService;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class WebSocketController {
    private static final Logger log = LoggerFactory.getLogger(WebSocketController.class);
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private RoomService roomService;
    @Autowired
    private WebSocketEventListener webSocketEventListener;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public WebSocketController() {
    }

    @MessageMapping({"/joinGame"})
    public void joinGame(Player player, SimpMessageHeaderAccessor headerAccessor) {
        String sessionId = headerAccessor.getSessionId();
        log.info("玩家通过WebSocket加入游戏：{}，会话ID: {}", player.getUsername(), sessionId);
        this.webSocketEventListener.addSessionPlayer(sessionId, player);

        String playerKey = "game:player:" + player.getId();
        String roomId = (String)this.redisTemplate.opsForValue().get(playerKey);
        if (roomId != null) {
            List<Player> roomPlayers = this.roomService.getPlayersInRoom(roomId);
            this.messagingTemplate.convertAndSend("/topic/room/" + roomId, roomPlayers);
            log.info("玩家 {} 已通过HTTP加入房间 {}，通过WebSocket连接成功", player.getUsername(), roomId);
        } else {
            RoomJoinResult result = this.roomService.joinRoom(player);
            if (result.isSuccess()) {
                List<Player> roomPlayers = this.roomService.getPlayersInRoom(result.getRoomId());
                this.messagingTemplate.convertAndSend("/topic/room/" + result.getRoomId(), roomPlayers);
                log.info("玩家 {} 成功加入房间 {}", player.getUsername(), result.getRoomId());
            } else {
                log.warn("玩家 {} 加入房间失败: {}", player.getUsername(), result.getMessage());
                this.messagingTemplate.convertAndSendToUser(player.getId(), "/queue/error", result.getMessage());
            }
        }

    }

    @MessageMapping({"/leaveGame"})
    public void leaveGame(Player player, SimpMessageHeaderAccessor headerAccessor) {
        String sessionId = headerAccessor.getSessionId();
        log.info("玩家主动下线：{}，会话ID: {}", player.getUsername(), sessionId);
        this.webSocketEventListener.removeSessionPlayer(sessionId);
        if (this.roomService.leaveRoom(player.getId())) {
            String roomId = player.getRoomId();
            List<Player> remainingPlayers = this.roomService.getPlayersInRoom(roomId);
            this.messagingTemplate.convertAndSend("/topic/room/" + roomId, remainingPlayers);
            log.info("房间 {} 剩余玩家数量: {}", roomId, remainingPlayers.size());
        }

    }

    @MessageMapping({"/updatePlayer"})
    public void updatePlayer(Player player, SimpMessageHeaderAccessor headerAccessor) {
        String sessionId = headerAccessor.getSessionId();
        log.info("玩家移动：{}，位置：({}, {})，会话ID: {}", new Object[]{player.getUsername(), player.getPosition().getX(), player.getPosition().getY(), sessionId});
        this.webSocketEventListener.updatePlayerHeartbeat(player.getId());
        if (this.roomService.updatePlayerPosition(player.getId(), player)) {
            String roomId = player.getRoomId();
            List<Player> roomPlayers = this.roomService.getPlayersInRoom(roomId);
            this.messagingTemplate.convertAndSend("/topic/room/" + roomId, roomPlayers);
        }

    }

    @MessageMapping({"/heartbeat"})
    public void heartbeat(Player player, SimpMessageHeaderAccessor headerAccessor) {
        String sessionId = headerAccessor.getSessionId();
        log.info("收到玩家 {} 心跳，会话ID: {}", player.getUsername(), sessionId);
        this.webSocketEventListener.updatePlayerHeartbeat(player.getId());
    }
}
